/* 
 * File:   LightStack.cpp
 * Author: Lucky
 * 
 * Created on 28. září 2011, 12:59
 */

#include <iostream>
#include <iomanip>
#include "LightStack.h"
#include "Node.h"
#include "LightException.h"

LightStack::LightStack() {
    m_length = 0;
    m_top = 0;
}

LightStack::LightStack(const LightStack& orig) {
    throw "unsupported operation"; //Not implemented
}

LightStack::~LightStack() {
    delete m_top;
}

void LightStack::push(Node* n) {
    Element* el = new Element();
    el->prev = m_top;
    el->value = n;
    el->popped = false;
    
    m_top = el;
    ++m_length;
}

Node* LightStack::pop() {
    if (m_length == 0) throw new LightException("Stack is empty!");
    Element* el = m_top;
    
    Node* node = el->value;
    if (el->popped) {
        node->setPopped();
        m_top = m_top->prev;
        --m_length;
        delete el;
    } else {
        el->popped = true;
    }
    
    return node;
}

int LightStack::getLength() const {
    return m_length;
}

bool LightStack::isEmpty() const {
    return m_length == 0;
}

void LightStack::printActiveCoordinates() const {
    Element* el = m_top;
    std::cout << "Posloupnost souradnic: ";
    while (el != 0) {
        if (el->popped) {
            if (el->value->getAction() == SWITCH) {
               // Coordinate c = el->value->getCoordinate();
                std::cout << el->value->x << "X" <<  el->value->y << "   ";
            }
        }
        el = el->prev;
    }
    std::cout << std::endl;
}

Result* LightStack::getResult() const {
    int steps = 0;
    Element* el = m_top;
    while (el != 0) {
        if (el->popped && el->value->getAction() == SWITCH) {
            ++steps;
        }
        el = el->prev;
    }
    
    int* coords = new int[2*steps];
    int pointer = 0;
    el = m_top;
    while (el != 0) {
        if (el->popped && el->value->getAction() == SWITCH) {
            coords[pointer++] = el->value->x;
            coords[pointer++] = el->value->y;
        }
        el = el->prev;
    }
    
    return new Result(steps, coords);
}

